package com.sekla.thread.pool.sdk.trigger.listener;

import com.alibaba.fastjson.JSON;
import com.sekla.thread.pool.sdk.domain.IDynamicThreadPoolService;
import com.sekla.thread.pool.sdk.domain.model.ThreadPoolConfigEntity;
import com.sekla.thread.pool.sdk.registry.IRegistry;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 动态线程池变更监听
 */
public class ThreadPoolConfigAdjustListener implements MessageListener<ThreadPoolConfigEntity> {
    private Logger logger = LoggerFactory.getLogger(ThreadPoolConfigAdjustListener.class);

    private final IDynamicThreadPoolService dynamicThreadPoolService;

    private final IRegistry registry;

    public ThreadPoolConfigAdjustListener(IDynamicThreadPoolService dynamicThreadPoolService, IRegistry registry) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.registry = registry;
    }

    @Override
    public void onMessage(CharSequence channel, ThreadPoolConfigEntity msg) {
        logger.info("动态线程池，调整线程池配置。线程池名称:{},核心线程池数量:{},最大线程数量:{}", msg.getThreadPoolName(),
                msg.getCorePoolSize(), msg.getMaximumPoolSize());

        // 更新线程池
        dynamicThreadPoolService.updateThreadPoolConfig(msg);

        // 更新后上报最新数据
        List<ThreadPoolConfigEntity> threadPoolConfigEntities = dynamicThreadPoolService.queryThreadPoolList();
        registry.reportThreadPool(threadPoolConfigEntities);

        ThreadPoolConfigEntity threadPoolConfigEntityCurrent = dynamicThreadPoolService.queryThreadPoolConfigByName(msg.getThreadPoolName());
        registry.reportThreadPoolConfigParameter(threadPoolConfigEntityCurrent);

        logger.info("动态线程池，上报线程配置:{}", JSON.toJSONString(msg));
    }
}
